package com.kate.mall.oauth.service;

import cn.hutool.core.map.MapUtil;
import com.kate.mall.common.utils.ListMap2ListVoUtils2;
import com.kate.mall.oauth.domain.ClientDto;
import com.kate.mall.oauth.feign.NdmallMemeberFeignClient;
import com.kate.mall.common.utils.R;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.ClientRegistrationException;
import org.springframework.security.oauth2.provider.NoSuchClientException;
import org.springframework.security.oauth2.provider.client.BaseClientDetails;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Description: 用一句话描述
 * @Auther: 陈超*kate
 * @Date: 2021/11/1 09:21
 */
@Component
public class ClientDetailsServiceImpl implements ClientDetailsService {
    @Resource
    private NdmallMemeberFeignClient ndmallMemeberFeignClient;

    @Resource
    private ListMap2ListVoUtils2 listMap2ListVoUtils;
    @Override
    public ClientDetails loadClientByClientId(String clientId) throws ClientRegistrationException {
        try {
            R clientR = ndmallMemeberFeignClient.getClientById(clientId);
//            List<Map> clientMap = new ArrayList<>(1);
//            clientMap.add(MapUtil.get(clientR,"sysOauthClient",Map.class));
//            List<ClientDto> clientDtoList = listMap2ListVoUtils.map2Vo(clientMap, null,ClientDto.class);
            Map clientMap = MapUtil.get(clientR,"sysOauthClient",Map.class);
            ClientDto clientDto = listMap2ListVoUtils.map2Vo(clientMap, null,ClientDto.class);
            if (clientDto != null ) {
                BaseClientDetails clientDetails = new BaseClientDetails(
                        clientDto.getClientId(),
                        clientDto.getResourceIds(),
                        clientDto.getScope(),
                        clientDto.getAuthorizedGrantTypes(),
                        clientDto.getAuthorities(),
                        clientDto.getWebServerRedirectUri()
                );
                clientDetails.setClientSecret(clientDto.getClientSecret());                   //【1】
                clientDetails.setAccessTokenValiditySeconds(clientDto.getAccessTokenValidity());
                clientDetails.setRefreshTokenValiditySeconds(clientDto.getRefreshTokenValidity());
                return clientDetails;
            } else {
                throw new NoSuchClientException("No client with requested id: " + clientId);
            }
        } catch (EmptyResultDataAccessException var4) {
            throw new NoSuchClientException("No client with requested id: " + clientId);
        }
    }
}
